package com.fly.locks.thread.semaphore;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class SemaphoreThread implements Runnable
{
    // 表示有2个许可.
    Semaphore sem = new Semaphore(2);
    
    @Override
    public void run()
    {
        try
        {
            sem.acquire(); // 默认使用一个许可.
            log.info("{} I get it.", Thread.currentThread());
            TimeUnit.SECONDS.sleep(3);
            log.info("{} I release it.", Thread.currentThread());
        }
        catch (InterruptedException e)
        {
            log.error(e.getMessage());
        }
        finally
        {
            sem.release();
        }
    }
}
